#include <connector.hpp>

static Connector* s_Connector = nullptr;

Connector* Connector::Instance()
{
	if (s_Connector == nullptr)
	{
		s_Connector = new Connector();
	}
	return s_Connector;
}

Connector::Connector()
	: m_DataSeq(0)
	, m_OutSize(0)
{
	m_OutData = (char*)malloc(SOCK_BUFF_SIZE);
}

Connector::~Connector()
{
	free(m_OutData);
}

void Connector::Create(int port, TcpServerClient* (*pTcpClientCreator)())
{
	TcpServer* server = new TcpServer(port, pTcpClientCreator);
	m_Servers[port]	  = server;
	server->Start();
}

void Connector::Create(const char* ip, int port, UdpRecverClient* pUdpClient)
{
	if (ip != nullptr)
	{
		UdpSender* udpSender = new UdpSender(ip, port);
		m_UdpSender[port]	 = udpSender;
	}

	if (pUdpClient != nullptr)
	{
		UdpRecver* udpRecver = new UdpRecver(port, pUdpClient);
		m_UdpRecver[port]	 = udpRecver;
		udpRecver->Start();
	}
}

void Connector::Send(int port, char* data, int size)
{
	TcpServer* server = m_Servers[port];
	if (server == nullptr)
	{
		LOGE("Tcp Server is nullptr.\n");
		return;
	}

	server->Send(data, size);
}

void Connector::Send(int port, uint32_t data_type, char* data, int size)
{
	int ret = m_Protocol.Pack(m_OutData, &m_OutSize, data, size, m_DataSeq, data_type);
	if (ret != 0)
	{
		LOGE("protocol pack error.\n");
		return;
	}
	m_DataSeq++;
	Send(port, m_OutData, m_OutSize);
}

void Connector::SendTo(int port, char* data, int size)
{
	UdpSender* udpSender = m_UdpSender[port];
	if (udpSender == nullptr)
	{
		LOGE("Udp sendder is nullptr.\n");
		return;
	}
	udpSender->SendData(data, size);
}

void Connector::SendTo(int port, uint32_t data_type, char* data, int size)
{
	int ret = m_Protocol.Pack(m_OutData, &m_OutSize, data, size, m_DataSeq, data_type);
	if (ret != 0)
	{
		LOGE("protocol pack error.\n");
		return;
	}
	m_DataSeq++;
	SendTo(port, m_OutData, m_OutSize);
}